import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { STColumn, STColumnSort, STColumnTag, STComponent, STData, STPage, STRes } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSelectWidgetSchema } from '@delon/form';
import { _HttpClient, SettingsService } from '@delon/theme';
import format from 'date-fns/format';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-business-statistics',
  templateUrl: './statistics.component.html'
})
export class BusinessStatisticsComponent implements OnInit {
  url = `api/statistics/summary`;
  isAdmin = false;
  today = new Date();
  ps = 50;
  pi = 1;
  shopId = 1;
  limitFlag = '';

  @ViewChild('sf', { static: false }) private sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      companyId: {
        type: 'string',
        title: '',
        readOnly: !this.isAdmin,
        ui: {
          widget: 'select',
          placeholder: '所属组织',
          asyncData: () =>
            this.loadCompany().pipe(
              map((value: any) => {
                return value;
              })
            ),
          change: i => {
            this.updateShop(i);
          }
        } as SFSelectWidgetSchema
      },
      shopId: {
        type: 'string',
        title: '',
        readOnly: !this.isAdmin,
        ui: {
          widget: 'select',
          placeholder: '店铺',
          showSearch: true
        } as SFSelectWidgetSchema
      },
      limitFlag: {
        type: 'string',
        title: '',
        enum: [
          { label: '全部', value: '' },
          { label: '新店', value: '1' },
          { label: '受限', value: '2' }
        ],
        //default: '',
        ui: {
          widget: 'select',
          placeholder: '售后承担',
          showSearch: false
        } as SFSelectWidgetSchema
      }
    }
  };
  limitTag: STColumnTag = {
    0: { text: '新店', color: 'green' },
    1: { text: '受限', color: 'red' }
  };
  transTag: STColumnTag = {
    0: { text: '否', color: 'green' },
    1: { text: '是', color: 'red' }
  };
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '店铺名称',
      index: 'fordeal_shop_name',
      className: 'text-center',
      format: (item: STData, col: STColumn, index: number) => {
        return `<span title="店铺ID: ${item.shop_id}">${item.fordeal_shop_name}</span>`;
      }
    },
    { title: '所属组织', index: 'company_name', className: 'text-center', default: '-' },
    {
      title: '目前在售',
      index: 'shopStatistics.online',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.online',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '售后承担', optionalHelp: '' },
      index: 'shopStatistics.limit_flag',
      type: 'tag',
      tag: this.limitTag,
      default: '-',
      width: 90
    },
    {
      title: { text: '差评ODR', optionalHelp: '近180天差评ODR' },
      // index: 'shopStatistics.negative_odr',
      format: (item: STData, col: STColumn, index: number) => {
        let num = parseFloat(item.shopStatistics.negative_odr) * 100;
        let num2 = parseFloat(item.shopStatisticsYesterday.negative_odr) * 100;
        return `<span style="color:${num > num2 ? 'red' : 'black'}" title="前日数据：${num2.toFixed(2)}%">${num.toFixed(2)}%</span>`;
      },
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.negative_odr',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '缺货ODR', optionalHelp: '近7天缺货ODR' },
      // index: 'shopStatistics.lack_odr',
      format: (item: STData, col: STColumn, index: number) => {
        let num = parseFloat(item.shopStatistics.lack_odr) * 100;
        let num2 = parseFloat(item.shopStatisticsYesterday.lack_odr) * 100;
        return `<span style="color:${num > num2 ? 'red' : 'black'}" title="前日数据：${num2.toFixed(2)}%">${num.toFixed(2)}%</span>`;
      },
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.lack_odr',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '总评价', optionalHelp: '店铺总评论数' },
      format: (item: STData, col: STColumn, index: number) => {
        return `<span style="color:red">${item.shopStatistics.comment_total}</span>|<span style="color:green">${item.shopStatistics.negative_comment_total}</span>`;
      },
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '近180天\n评价', optionalHelp: '近180天评论数｜近180天差评数' },
      index: 'shopStatistics.negative_comment_count',
      className: 'text-center',
      format: (item: STData, col: STColumn, index: number) => {
        return `<span style="color:red">${item.shopStatistics.comment_count}</span>|<span style="color:green">${item.shopStatistics.negative_comment_count}</span>`;
      },
      default: '-'
    },
    {
      title: { text: '昨日流量', optionalHelp: '昨日店铺内所有商品详情页被浏览次数的累加' },
      index: 'shopStatistics.yesterday_view_count',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.yesterday_view_count',
        reName: { ascend: 'asc', descend: 'desc' }
      },
      format: (item: STData, col: STColumn, index: number) => {
        let num = item.shopStatistics.yesterday_view_count;
        let num2 = item.shopStatisticsYesterday.yesterday_view_count;
        return `<span style="color:${num < num2 ? 'red' : 'black'}" title="前日数据：${num2}">${num}</span>`;
      }
    },
    {
      title: { text: '切实库', optionalHelp: '是否切换为实库销售' },
      index: 'shopStatistics.trans_flag',
      className: 'text-center',
      type: 'tag',
      tag: this.transTag,
      default: '-'
    },
    {
      title: { text: '切实库时间', optionalHelp: '最近切实库时间' },
      index: 'shopStatistics.trans_at',
      format: (item: STData, col: STColumn, index: number) => {
        if (item.shopStatistics.trans_at == '') {
          return '--';
        }
        return `<span style="color: red">${format(new Date(item.shopStatistics.trans_at), 'yyyy-MM-dd HH:mm:ss')}</span>`;
      },
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '切实库次数', optionalHelp: '近60天切实库次数' },
      index: 'shopStatistics.trans_times',
      className: 'text-center',
      format: (item: STData, col: STColumn, index: number) => {
        if (item.shopStatistics.trans_times == 0) {
          return '--';
        }
        return `${item.shopStatistics.trans_times}`;
      },
      default: '-',
      sort: {
        key: 'ShopStatistics.trans_times',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '1-15天售后', optionalHelp: this.formatPreOptionHelper() },
      index: 'shopStatistics.pre_after_sale_count',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.pre_after_sale_count',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '16-31天售后', optionalHelp: this.formatCOptionHelper() },
      index: 'shopStatistics.c_after_sale_count',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.c_after_sale_count',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '周流量', optionalHelp: '近7天商品浏览量｜加购件数｜订单确认数' },
      format: (item: STData, col: STColumn, index: number) => {
        return `${item.shopStatistics.ctm_item_view_pv_seven_days}|${item.shopStatistics.cart_item_num_seven_days}|${item.shopStatistics.item_verified_cnt_seven_days}`;
      },
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '月流量', optionalHelp: '近30天商品浏览量｜加购件数｜订单确认数' },
      format: (item: STData, col: STColumn, index: number) => {
        return `${item.shopStatistics.ctm_item_view_pv_thirty_days}|${item.shopStatistics.cart_item_num_thirty_days}|${item.shopStatistics.item_verified_cnt_thirty_days}`;
      },
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '商品上新', optionalHelp: '近7天商品上新数量｜无商品货号数' },
      // index: 'shopStatistics.online',
      format: (item: STData, col: STColumn, index: number) => {
        return `${item.shopStatistics.merchant_new}|${item.shopStatistics.merchant_not_item_code}`;
      },
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '沉淀商品', optionalHelp: '近30天总曝光量5000以上' },
      index: 'shopStatistics.item_view_thirty_days',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.item_view_thirty_days',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '缺货次数', optionalHelp: '近7天缺货次数' },
      index: 'shopStatistics.cancel_count',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopStatistics.cancel_count',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '售后成本', optionalHelp: '' },
      index: 'shopStatistics.after_sale_cost',
      format: (item: STData, col: STColumn, index: number) => {
        let num = parseFloat(item.shopStatistics.after_sale_cost) * 100;
        return `${num.toFixed(2)}%`;
      },
      default: '-',
      sort: {
        key: 'ShopStatistics.after_sale_cost',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    }
  ];

  res: STRes = {
    reName: {
      total: 'data.total',
      list: 'data.list'
    }
  };

  paginate: STPage = {
    showSize: true,
    pageSizes: [10, 20, 50, 100]
  };

  formatPreOptionHelper(): string {
    if (this.today.getDay() <= 3) {
      return `上月3日至19日售后订单数量`;
    } else if (this.today.getDay() > 3 && this.today.getDay() <= 19) {
      return `本月3日至昨日售后订单数量`;
    } else {
      return `本月3日至18日售后订单数量`;
    }
  }

  formatCOptionHelper(): string {
    if (this.today.getDay() <= 3) {
      return `上月19日至昨日售后订单数量`;
    } else if (this.today.getDay() > 3 && this.today.getDay() <= 19) {
      return `上月19日至本月2日售后订单数量`;
    } else {
      return `本月19日至昨日售后订单数量`;
    }
  }

  shopList: any = {};
  loadCompany(): Observable<Array<{ label: any; value: any }>> {
    return this.http.get(`api/shop_map`).pipe(
      map((resp: any) => {
        let arr: Array<{ label: any; value: any }> = [];
        let list = resp.data['companies'];
        if (list && list.length) {
          list.forEach((element: { company_name: any; ID: any }) => {
            arr.push({ label: element.company_name, value: element.ID });
            this.shopList[element.ID] = [];
          });
        }
        let shops: any[] = resp.data['shops'];
        shops.forEach(shop => {
          this.shopList[shop['company_id']].push({ label: shop['fordeal_shop_name'], value: shop['shop_id'] });
        });
        return arr;
      })
    );
  }

  constructor(private http: _HttpClient, private cdr: ChangeDetectorRef, private settingService: SettingsService) {
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
      let companyId = this.searchSchema?.properties?.companyId;
      if (companyId) {
        companyId.readOnly = false;
      }
      let shopId = this.searchSchema?.properties?.shopId;
      if (shopId) {
        shopId.readOnly = false;
      }
    }

    if (!this.isAdmin) {
      this.searchSchema = {
        properties: {
          limitFlag: {
            type: 'string',
            title: '',
            enum: [
              { label: '全部', value: '' },
              { label: '新店', value: '1' },
              { label: '受限', value: '2' }
            ],
            //default: '',
            ui: {
              widget: 'select',
              placeholder: '售后承担',
              showSearch: false
            } as SFSelectWidgetSchema
          }
        }
      };
    }
  }

  ngOnInit = (): void => {};

  search(): void {
    this.pi = 1;
    this.ps = 30;
    this.shopId = 0;
    this.limitFlag = '';
  }

  reset(e: any) {
    e.preventDefault();
    console.log('--reset--');
    this.pi = 1;
    this.ps = 30;
    this.shopId = 0;
    this.limitFlag = '';
  }

  updateShop(companyID: number): void {
    let property = this.sf.getProperty('/shopId');
    // @ts-ignore
    property.schema.enum = this.shopList[companyID];
    // @ts-ignore
    property.widget.reset('');
  }
}
